<?php
/**
 * Created by PhpStorm.
 * User: huyang
 * Date: 2017/6/7
 * Time: 下午6:05
 */
class Account extends Web_Controller
{
    protected $root = null;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('User_model', 'user_model');
        $this->load->library('session');
        $this->root = './upload/msg_file/';

        // 验证码
        $this->load->library('RedisDriver', 'redisdriver');
        $this->redisdriver->connect();
    }

    public function index() {
        $this->login();
    }

    // 登录
    public function login() {
        $data['base_url'] = $this->config->item('base_url');
        $data['back_url'] = $this->input->get('back_url');
        $this->loadView('header',$data);
        $this->loadView('account_login');
    }


    public function register() {
        $data['base_url'] = $this->config->item('base_url');
        $data['back_url'] = $this->input->get('back_url');
        $this->loadView('header', $data);
        $this->loadView('account_register');

    }

    //商城首页点击'我的'跳转
    public function myInfo()
    {
        $data['base_url'] = $this->config->item('base_url');
        //获取用户信息,未登录不重定向
        $user = $this->userSession(false);
        if(! empty($user))
        {
            $data['uid'] = $user->uid;
            $data['mobile'] = $user->mobile;
            $data['username'] = $user->username;
            $this->load->model('User_model');
            $info  = $this->User_model->checkCard($user->uid);
            $data['cardid'] = $info['cardid'];
        }
        $this->loadView('header', $data);
        $this->loadView('my_info');
    }

    //重置密码/忘记密码
    public function resetPassword()
    {
        $data['base_url'] = $this->config->item('base_url');
        $data['back_url'] = $this->input->get('back_url');
        $this->loadView('header', $data);
        $this->loadView('account_resetpassword');
    }

    //注销当前用户
    public function logout()
    {
        //清除session中的web_user
        $this->session->unset_userdata('web_user');
        $this->session->unset_userdata('openid');
        $this->session->unset_userdata('admin_web_user');
        $this->login();
    }

    //  -------------------api 接口---------------
    // 用户注册
    public function add() {
        $mobile = $this->input->post('mobile');
        $password = $this->input->post('password');
        $captcha = $this->input->post('captcha');
        if (empty($mobile) || empty($password) || empty($captcha)) {
            $this->response(array('result' => 10001, 'message' => '账号，密码，验证码不能为空'));
        }

        // 账号已存在
        $row = $this->user_model->checkMobile($mobile);
        if (!is_null($row)) {
            $this->response(array('result' => 1, 'message' => '账号已存在'));
        }

        // 密码长度验证
        if (strlen($password) < 6 || strlen($password) > 12) {
            $this->response(array('result' => 4, 'message' => '请设置6-12位密码'));
        }

        // 验证码
        $true_captcha = $this->redisdriver->getStr('captcha:' . $mobile);

        if (is_null($true_captcha)) {
            $this->response(array('result' => 2, 'message' => '验证码失效'));

        }
        if ($true_captcha != $captcha) {
            $this->response(array('result' => 3, 'message' => '验证码错误'));
        }


        $ip = $_SERVER["REMOTE_ADDR"];
        $data = array(
            'mobile' => $mobile,
            'password' => sha1($password),
            'register_time' => time(),
            'last_time' => time(),
            'ip' => $ip
        );
        $uid = $this->user_model->add($data);

        // session 存储 uid
        $this->session->web_user = (object) array('uid' => $uid, 'mobile' => $mobile);
        if (!is_null($uid)) {
            //删除验证码缓存
            $this->redisdriver->delStr('captcha:' . $mobile);
            $this->response(array('result' => 0, 'message' => '注册成功！'));
        } else {
            $this->response(array('result' => 10002, 'message' => '错误！'));
        }


    }


    // 校验密码 登录
    public function checkLogin() {
        $mobile = $this->input->post('mobile');
        $password = $this->input->post('password');
        if (empty($mobile) || empty($password)) {
            $this->response(array('result' => 10001, 'message' => '账号，密码不能为空'));
        }

        $row = $this->user_model->confirmPassword($mobile, $password); // row 为数组
        if (is_null($row)) {
            $this->response(array('result' => 1, 'message' => '账号或密码错误'));
        }

        $this->session->web_user = (object) array('uid' => $row['uid'], 'username' => $row['username'], 'mobile' => $row['mobile']);
        //更新最后登陆时间
        $ip = $_SERVER["REMOTE_ADDR"];
        $this->user_model->updateLasttimeByUid($row['uid'], $ip);

        $this->response(array('result' => 0,'message'=>$this->session->web_user));

    }

    // 修改密码, 然后前台登录
    public function updatePassword() {

        $mobile = $this->input->post('mobile');
        $password = $this->input->post('password');
        $captcha = $this->input->post('captcha');
        if (empty($mobile) || empty($password) || empty($captcha)) {
            $this->response(array('result' => 10001, 'message' => '账号，密码，验证码不能为空'));
        }

        // 账号不存在
        $row = $this->user_model->checkMobile($mobile);
        if (is_null($row)) {
            $this->response(array('result' => 1, 'message' => '账号不存在'));
        }

        // 密码长度验证
        if (strlen($password) < 6 || strlen($password) > 12) {
            $this->response(array('result' => 4, 'message' => '请设置6-12位密码'));
        }

        // 验证码
        $true_captcha = $this->redisdriver->getStr('captcha:' . $mobile);

        if (is_null($true_captcha)) {
            $this->response(array('result' => 2, 'message' => '验证码无效'));
        }

        if ($true_captcha != $captcha) {
            $this->response(array('result' => 3, 'message' => '验证码错误'));
        }

        $res = $this->user_model->updatePassword($mobile, $password);
        if($res === false)
        {
            $this->response(array('result' => 4, 'message' => '密码修改失败'));
        }
        else
        {
            $this->session->web_user = (object) array('uid' => $row->uid, 'username' => $row->username, 'mobile' => $row->mobile);
            //更新最后登陆时间
            $this->user_model->updateLasttimeByUid($row->uid, $_SERVER["REMOTE_ADDR"]);
            //删除验证码缓存
            $this->redisdriver->delStr('captcha:' . $mobile);
            $this->response(array('result' => 0, 'message' => '密码修改成功'));
        }
    }

    /**
     * 短信网关
     * type: 0-注册验证 1-修改密码验证
     * @return [type] [description]
     */
    public function sms_port() {
        $this->load->helper('json');
        $this->load->helper('http');
        $this->load->helper('sms');
        $this->load->library('RedisDriver', 'redisdriver');
        $this->redisdriver->connect();

        $phone = $this->input->get('phone');
        $type = $this->input->get('type');


        //手机号校验
        if (!ctype_digit($phone)) {
            $this->response(array('errcode' => 10001,'errmsg' => '手机号出错'));
        }

        //注册时手机号已存在，不能发送验证码
        if($type == 0 && $this->user_model->checkMobile($phone) != null)
        {
            $this->response(array('errcode' => 10002, 'errmsg' => '该手机号已注册'));
        }
        //修改时手机号不存在，不能发送验证码
        if($type == 1 && $this->user_model->checkMobile($phone) == null)
        {
            $this->response(array('errcode' => 10003, 'errmsg' => '该手机号未注册'));   
        }

        // 一分钟内禁止重复发送短信
        $phonenum = $this->redisdriver->getStr('phone:' . $phone);
        if ($phone == $phonenum) {
            $this->response(array('errcode' => 10020,'errmsg' => '您发送的次数过于频繁'));
        }

        // 验证码接口做次数限制 防止恶意攻击 （同一手机号只能获取10次短信验证码）
        $flag = $this->get_authentication_code($phone);
        if (!$flag) {
            $this->response(array('errcode' => 10004, 'errmsg' => '您今日获取短信验证码的次数过多，不发送验证码！'));
        }


        $num = rand(1000, 9999);
        $expire = 60;//十分钟有效期
        $this->redisdriver->setStr('captcha:' . $phone, $num, $expire);
        $response = json_decode(sms_juhe(1, $phone, array('code' => $num)));

        if ($response->error_code == 0) {
            // 存储该手机号  防止重复发送
            $time = 60;
            $this->redisdriver->setStr('phone:' . $phone, $phone, $time);
        }

        $arr = array(
            'errcode' => $response->error_code,
            'errmsg' => $response->reason
        );

        $this->response($arr);
    }

    // PC端用
    public function sms_port_pc() {
        $this->load->helper('json');
        $this->load->helper('http');
        $this->load->helper('sms');
        $this->load->library('RedisDriver', 'redisdriver');
        $this->redisdriver->connect();

        $phone = $this->input->post('phone');
        $type = $this->input->post('type');
        $captcha = $this->input->post('captcha');

        if (empty($captcha)) {
            $this->response(array('errcode' => 10031, 'errmsg' => '验证码为空'));
        }
        // 验证验证码
        $cap_word = $this->session->cap_word;
        if ($captcha != $cap_word) {
            $this->response(array('errcode' => 10032, 'errmsg' => '验证码错误'));

        }


        //手机号校验
        if (!ctype_digit($phone)) {
            $this->response(array('errcode' => 10001,'errmsg' => '手机号出错'));
        }

        //注册时手机号已存在，不能发送验证码
        if($type == 0 && $this->user_model->checkMobile($phone) != null)
        {
            $this->response(array('errcode' => 10002, 'errmsg' => '该手机号已注册'));
        }
        //修改时手机号不存在，不能发送验证码
        if($type == 1 && $this->user_model->checkMobile($phone) == null)
        {
            $this->response(array('errcode' => 10003, 'errmsg' => '该手机号未注册'));
        }

        // 一分钟内禁止重复发送短信
        $phonenum = $this->redisdriver->getStr('phone:' . $phone);
        if ($phone == $phonenum) {
            $this->response(array('errcode' => 10020,'errmsg' => '您发送的次数过于频繁'));
        }

        // 验证码接口做次数限制 防止恶意攻击 （同一手机号只能获取10次短信验证码）
        $flag = $this->get_authentication_code($phone);
        if (!$flag) {
            $this->response(array('errcode' => 10004, 'errmsg' => '您今日获取短信验证码的次数过多，不发送验证码！'));
        }


        $num = rand(1000, 9999);
        $expire = 60;//一分钟有效期
        $this->redisdriver->setStr('captcha:' . $phone, $num, $expire);
        $response = json_decode(sms_juhe(1, $phone, array('code' => $num)));

        if ($response->error_code == 0) {
            // 存储该手机号  防止重复发送
            $time = 60;
            $this->redisdriver->setStr('phone:' . $phone, $phone, $time);
        }

        $arr = array(
            'errcode' => $response->error_code,
            'errmsg' => $response->reason
        );

        $this->response($arr);
    }


    // 短信验证防止恶意攻击
    public function get_authentication_code($tel) {
//        $ip = $_SERVER["REMOTE_ADDR"];//ip

        $count = 10;
        // 判断数据是否超过了限制
        $tel_num = $this->checkTel($tel, $count);
        if ($tel_num < $count) {
            return true;//符合发送条件，发送验证码的操作
        } else {
            //当不发送验证码时，将数据存入文件，用于方便查询
            $data = $tel . "|";
            if ($tel_num >= $count) {
                $data = $data . "B@";
            }

            $this->wirteFile("", $data);
            return false;
        }
    }


    //检测Tel在文件中出现的次数
    Private function checkTel($tel, $count)
    {
        $fileName = "Tel_" . date("Ymd", time()) . ".dat";
        $filePath = ($this->root) . $fileName;
//        echo "<br/>tel:".readfile($filePath);
//        echo "<br/>tel:".fread(fopen($filePath,"r"),filesize($filePath));
        $c_sum = 0;
        if (file_exists($filePath)) {
            $arr = file_get_contents($filePath);
            $row = explode("|", $arr);
            $countArr = array_count_values($row);
            if (array_key_exists($tel, $countArr)) {
                $c_sum = $countArr[$tel];
                if ($c_sum <= $count) {
                    $this->wirteFile($filePath, $tel . "|");
                }
                return $c_sum;
            } else {
                return 1;
            }
        } else {
            $this->wirteFile($filePath, $tel . "|");
            return $c_sum;
        }
    }


    /**
     * 将数据写入本地文件
     * @param $filePath 要写入文件的路径
     * @param $data 写入的数据
     */
    Private function wirteFile($filePath, $data)
    {
        try {
            if (!is_dir($this->root)) {//判断文件所在目录是否存在，不存在就创建
                mkdir($this->root, 0777, true);
            }
            if ($filePath == "") {//此处是不发送验证码时，记录日志创建的文件
                $filePath = ($this->root) . "N" . date("Ymd", time()) . ".dat";
            }
            //写入文件操作
            $fp = fopen($filePath, "a+");//得到指针
            fwrite($fp, $data);//写
            fclose($fp);//关闭

            //清除缓存并再次检查文件大小
            clearstatcache();
        } catch (Exception $e) {
            print $e->getMessage();
        }
    }


}



?>